// eslint-disable-next-line import/no-extraneous-dependencies
import { parse } from 'url';

// mock userCouponDataSource
const genList = (current, pageSize) => {
  const userCouponDataSource = [];

  for (let i = 0; i < pageSize; i += 1) {
    const index = (current - 1) * 10 + i;
    userCouponDataSource.push({
      key: index,
      userCouponName: `优惠券名称 ${index}`,
      storeName: `商户名称 ${index}`,
      consumeTime: new Date(),
      consumeUserName: `核销人 ${index}`,
    });
  }
  userCouponDataSource.reverse();
  return userCouponDataSource;
};

let userCouponDataSource = genList(1, 100);

function getUserCoupon(req, res, u) {
  let realUrl = u;

  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const { current = 1, pageSize = 10 } = req.query;
  const params = parse(realUrl, true).query;
  let dataSource = [...userCouponDataSource].slice((current - 1) * pageSize, current * pageSize);

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }

      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(item => {
          if (parseInt(`${item.status}`, 10) === parseInt(s.split('')[0], 10)) {
            return true;
          }

          return false;
        }),
      );
    });
    dataSource = filterDataSource;
  }

  if (params.userCouponName) {
    dataSource = dataSource.filter(data => data.userCouponName.includes(params.userCouponName || ''));
  }
  if (params.storeName) {
    dataSource = dataSource.filter(data => data.storeName.includes(params.storeName || ''));
  }
  if (params.consumeUserName) {
    dataSource = dataSource.filter(data => data.consumeUserName.includes(params.consumeUserName || ''));
  }

  const result = {
    data: dataSource,
    total: userCouponDataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };
  return res.json(result);
}

export default {
  'GET /api/userCoupon': getUserCoupon,
};
